/*
 * Copyright (c) 2022. China Mobile (SuZhou) Software Technology Co.,Ltd. All rights reserved.
 * Lakehouse is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

import axios, { AxiosError, AxiosRequestConfig, AxiosResponse } from 'axios'
import { useUserStore } from '@/store/user/user'
import qs from 'qs'
import _ from 'lodash'
import { UserInfoDtos } from './modules/user/types'
import cookies from 'js-cookie'
import router from '@/router'

const $userStore = useUserStore()

// HTTP Response Body
interface HttpMessage<T> {
  code: number | string
  data: T
  message: string
}

let LOGIN_API = '/'
let METADATA_API = '/metadata/'
let SQL_CONSOLE_API = 'sql-console/'
let USER_API = 'users/'
let INSTANCE_API = 'instances/'

if (import.meta.env.MODE === 'development') {
  // use yapi mock server
  // LOGIN_API = 'http://100.71.9.12:7002/mock/1377/lakehouse/'
  // METADATA_API = 'http://100.71.9.12:7002/mock/1377/lakehouse/metadata/'
  // SQL_CONSOLE_API = 'http://100.71.9.12:7002/mock/1377/lakehouse/sql-console/'
  // USER_API = 'http://100.71.9.12:7002/mock/1377/lakehouse/users/'
  // INSTANCE_API = 'http://100.71.9.12:7002/mock/1377/lakehouse/instance/'

  // use local server
  // LOGIN_API = 'http://localhost:19086/lakehouse/'
  // METADATA_API = 'http://localhost:19086/lakehouse/metadata/'
  // SQL_CONSOLE_API = 'http://localhost:19086/lakehouse/sql-console/'
  // USER_API = 'http://localhost:19086/lakehouse/users/'
  // INSTANCE_API = 'http://localhost:19086/lakehouse/instances/'
} else {
  LOGIN_API = 'http://100.71.8.205:30086/lakehouse/'
  METADATA_API = 'http://100.71.8.205:30086/lakehouse/metadata/'
  SQL_CONSOLE_API = 'http://100.71.8.205:30086/lakehouse/sql-console/'
  USER_API = 'http://100.71.8.205:30086/lakehouse/users/'
  INSTANCE_API = 'http://100.71.8.205:30086/lakehouse/instances/'
}

/**
 * @description Log and display errors
 * @param {Error} error Error object
 */
const handleError = (res: AxiosResponse<any, any> | any) => {
  window.$message.error(res.data.message || res.message)
}

const err = (err: AxiosError): Promise<AxiosError> => {
  if (err.response?.status === 401 || err.response?.status === 504) {
    $userStore.setSessionId('')
    $userStore.setUserInfo({})
    cookies.set('language', '')
    router.push({ path: '/login' })
  }
  return Promise.reject(err)
}

const baseRequestConfig: AxiosRequestConfig = {
  baseURL:
    import.meta.env.MODE === 'development'
      ? '/'
      : import.meta.env.VITE_APP_PROD_WEB_URL + '/',
  timeout: 10000,
  transformRequest: (params: any) => {
    if (_.isPlainObject(params)) {
      return qs.stringify(params, { arrayFormat: 'repeat' })
    } else {
      return params
    }
  },
  paramsSerializer: (params: any) => {
    return qs.stringify(params, { arrayFormat: 'repeat' })
  }
}

const service = axios.create(baseRequestConfig)

service.interceptors.request.use((config: AxiosRequestConfig<any>) => {
  const sessionId = $userStore.getSessionId
  const userId = ($userStore.getUserInfo as UserInfoDtos).userId
  const language = cookies.get('language')

  config.headers = config.headers || {}
  if (sessionId) config.headers.sessionId = sessionId
  if (userId) config.headers.userId = userId
  if (language) config.headers.language = language

  return config
})

// The response to intercept
service.interceptors.response.use((res: AxiosResponse) => {
  // No code will be processed
  if (res.data.code === undefined) {
    return res.data
  }

  switch (res.data.code) {
    case 0:
      return res.data.data
    default:
      handleError(res)
      throw new Error()
  }
}, err)

export {
  service as axios,
  HttpMessage,
  LOGIN_API,
  METADATA_API,
  SQL_CONSOLE_API,
  USER_API,
  INSTANCE_API
}
